<div id="app">
    <el-row class="mt5 mb5">
        <el-button type="primary" icon="edit" @click="dialogFormVisible = true;">添加分类</el-button>
    </el-row>
    <el-dialog title="添加分类" :visible.sync="dialogFormVisible" :before-close="ai_dialog_close">
        <el-form :model="category" :rules="rules" ref="ruleForm">
            <el-form-item label="所属分类" prop="category" :label-width="formLabelWidth">
                <el-cascader expand-trigger="click" :options="categoryObjects" :change-on-select="true" @change="handleItemChange" :props="props" placeholder="顶级分类" v-model="treeValue" clearable></el-cascader>
            </el-form-item>
            <el-form-item label="分类名称" prop="title" :label-width="formLabelWidth">
                <el-input v-model="category.title" auto-complete="off" @keyup.enter.native="submit"></el-input>
            </el-form-item>
            <el-form-item label="序号" prop="index" :label-width="formLabelWidth">
                <el-input v-model="category.index" type="number" auto-complete="off" placeholder="越小越靠前" @keyup.enter.native="submit"></el-input>
            </el-form-item>
            <el-form-item label="分类图" :label-width="formLabelWidth" v-loading.body="avatarUploading">
                <el-upload action="/file/upload" :auto-upload=true name="file" list-type="picture-card" :show-file-list="false" :on-success="avatarUploadSuccess" :before-upload="avatarBeforeUpload">
                    <img v-if="category.avatarUrl" :src="category.avatarUrl" class="thumb">
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
            </el-form-item>
            <el-form-item label="Banner图" :label-width="formLabelWidth" v-loading.body="bannerUploading">
                <el-upload action="/file/upload" :auto-upload=true name="file" list-type="picture-card" :show-file-list="false" :on-success="bannerUploadSuccess" :before-upload="bannerBeforeUpload">
                    <img v-if="category.bannerUrl" :src="category.bannerUrl" class="thumb">
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="cancel">取 消</el-button>
            <el-button type="primary" @click="submit">确 定</el-button>
        </div>
    </el-dialog>
    <el-tree :data="categoryObjects" :props="defaultProps" default-expand-all :highlight-current="true" :render-content="renderContent" :expand-on-click-node="false">
    </el-tree>
</div>
<script>
new Vue({
    el: '#app',
    data: {
        categoryObjects: [], // 处理过后的tree
        categoryArray: [], // 原始category二维数组
        avatarUploading: false, // 正在上传头像
        bannerUploading: false, // 正在上传分类图
        defaultProps: {
            //tree props
            children: 'children',
            label: 'title'
        },
        treeValue: [],
        props: {
            //cascader props
            value: 'objectId',
            label: 'title',
            children: 'children'
        },
        category: {
            title: '分类',
            pid: '',
            avatarUrl: '',
            bannerUrl: ''
        },
        formLabelWidth: '120px',
        rules: {
            title: [{
                required: true,
                message: '请输入标题',
                trigger: 'blur'
            }]
        },
        isEdit: false, //编辑状态
        dialogFormVisible: false
    },
    mounted: function() {
        this.loadCategory();
    },
    methods: {
        loadCategory: function() {
            this.$http.post('../category/list').then(response => {
                this.categoryArray = response.body;
                // 在前端处理无限级分类
                this.categoryObjects = recursion(response.body, '');
            });
        },
        ai_dialog_close: function() {
            this.dialogFormVisible = false;
        },
        avatarBeforeUpload: function() {
            this.avatarUploading = true;
        },
        bannerBeforeUpload: function() {
            this.bannerUploading = true;
        },
        avatarUploadSuccess: function(res) {
            // console.log(res);
            // 回调设定图片路径，下同
            this.category.avatarUrl = res.url;
            // 关闭正在上传的动画
            this.avatarUploading = false;
        },
        bannerUploadSuccess: function(res) {
            // console.log(res);
            this.category.bannerUrl = res.url;
            this.bannerUploading = false;
        },
        handleItemChange: function(val) {
            this.category.pid = val.slice(-1).toString();
        },
        renderContent: function(createElement, { node, data, store }) {
            var self = this;
            return createElement('span', [
                createElement('span', node.label),
                createElement('span', {
                    attrs: {
                        style: "float: right; margin-right: 20px"
                    }
                }, [
                    createElement('el-button', {
                        attrs: {
                            size: "mini"
                        },
                        on: {
                            click: function() {
                                console.log(store);
                                console.info("点击了节点" + data.objectId + "的添加按钮");
                                self.category = data;
                                // 还有找到一直向上推进的父类
                                var treeValue = [];
                                parentWay(self.categoryArray, data.objectId, treeValue);
                                self.treeValue = treeValue.slice(0, -1);
                                self.dialogFormVisible = true;
                            }
                        }
                    }, "编辑"),
                    createElement('el-button', {
                        attrs: {
                            size: "mini"
                        },
                        on: {
                            click: function() {
                                // 确认操作
                                self.$confirm('确认删除分类吗?', '提示', {
                                    confirmButtonText: '确定',
                                    cancelButtonText: '取消',
                                    type: 'warning'
                                }).then(() => {
                                    // 判断是不是子分类
                                    if (data.children) {
                                        self.$alert('请先删除下属子分类', '该分类下还有子分类');
                                        return;
                                    }
                                    self.$http.post('/category/delete', { objectId: data.objectId }).then(response => {
                                        // 通过从网站重新加载一次数据，貌似从store元素会不生效
                                        // store.remove(data);
                                        self.loadCategory();
                                        self.$message({
                                            message: response.body.code === undefined ? '删除成功' : '删除失败 - code:' + response.body.code
                                        });
                                    });
                                }).catch(() => {});
                            }
                        }
                    }, "删除"),
                ]),
            ]);
        },
        cancel: function() {
            this.dialogFormVisible = false;
            this.loadCategory();
        },
        submit: function() {
            this.$refs.ruleForm.validate((valid) => {
                if (valid) {
                    // 验证通过
                    this.$http.post('./add', this.category).then(response => {
                        this.dialogFormVisible = false;
                        console.log(response);
                        // 重新加载分类刷新
                        this.loadCategory();
                        // reset form表单值
                        this.category = { pid: '' };
                        this.treeValue = [];
                        this.$message({
                            message: response.body.code === undefined ? '保存成功' : '保存失败 - code:' + response.body.code
                        });
                    });
                }
            });
        }
    }
});
</script>
<style type="text/css">
.el-tree {
    margin-top: 10px;
}
</style>